package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.behavior.service.AdBehaviorService;
import com.heima.client.article.IArticleClient;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.*;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AdBehaviorServiceImpl implements AdBehaviorService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IArticleClient articleClient;

    /**
     * 点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID) ;
        }
        // 从当前线程获取用户id
        Integer userId = ApThreadLocalUtil.get();
        //判断点赞类型 type 0文章  1动态   2评论
        if (dto.getType() == 0) {
            return getResponseResult(dto, userId);
        } else if (dto.getType() == 1) {
            //待定 动态 点赞
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
//        else if (dto.getType() == 2) {
//            //判断是 评论点赞 还是 评论回复点赞
//            // commentId == null && commentRepayId != null
//            if (dto.getCommentRepayId() != null && dto.getCommentId() == null) {
//                //回复评论点赞
//                return getRepayResult(dto, userId);
//            } else {
//                //评论点赞
//                return getResult(dto, userId);
//            }
//        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 点赞 type = 2   -文章回复评论点赞
     */
    private ResponseResult getResult(LikesBehaviorDto dto, Integer userId) {
        //点赞判断状态
        if (dto.getOperation() == 1) {
            //取消点赞 operation=1
            String key = "like_" + userId + "_" + dto.getCommentRepayId() + "_" + dto.getType();
            //判断是否存在数据
            if (!redisTemplate.hasKey(key)) {
                redisTemplate.opsForValue().set(key, String.valueOf(dto.getOperation()));
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else if (dto.getOperation() == 0) {
            //点赞 operation=1
            //记录用户行为存储到redis
            String key = "like_" + userId + "_" + dto.getCommentRepayId() + "_" + dto.getType();
            //判断是否存在数据
            if (!redisTemplate.hasKey(key)) {
                redisTemplate.opsForValue().set(key, String.valueOf(dto.getOperation()));
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //返回错误信息
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }


    /**
     * 评论 type = 2  -文章评论点赞
     *
     * @param dto
     * @param userId
     * @return
     */
    private ResponseResult getRepayResult(LikesBehaviorDto dto, Integer userId) {
        //点赞判断状态
        if (dto.getOperation() == 1) {
            //取消点赞 operation=1
            String key = "like_" + userId + "_" + dto.getCommentId() + "_" + dto.getType();
            //判断是否存在数据
            if (!redisTemplate.hasKey(key)) {
                redisTemplate.opsForValue().set(key, String.valueOf(dto.getOperation()));
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else if (dto.getOperation() == 0) {
            //点赞 operation=1
            //记录用户行为存储到redis
            String key = "like_" + userId + "_" + dto.getCommentId() + "_" + dto.getType();
            //判断是否存在数据
            if (!redisTemplate.hasKey(key)) {
                redisTemplate.opsForValue().set(key, String.valueOf(dto.getOperation()));
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //返回错误信息
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 点赞 type = 0  -文章点赞
     *
     * @param dto
     * @param userId
     * @return
     */
    private ResponseResult getResponseResult(LikesBehaviorDto dto, Integer userId) {
        //先获取Redis中的like_key  //key的组成：like_用户id_文章id_点赞类型
        String key = "like_" + userId + "_" + dto.getArticleId();
        //点赞判断状态
        if (dto.getOperation() == 1) {
            //取消点赞 operation=1 调用文章ap_article数据库 修改状态 点赞-1
            //在redis中删除 对应的数据
            //key的组成：like_用户id_文章id_点赞类型
            //删除 判断redis是否存在对应的数据
            if (redisTemplate.hasKey(key)) {
                //为true 删除 rides
                redisTemplate.delete(key);
                //调用文章ap_article数据库 修改状态 点赞-1
                //发起远程请求
                ArticleDto articleDto = getArticleDto(dto);
                //三元运算
                articleDto.setLikes(articleDto.getLikes() == null ? 0 : articleDto.getLikes() - 1);
                //发起远程请求
                ResponseResult result = articleClient.syncArticle(articleDto);
                if (result.getCode() != 200) {
                    throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
                }
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else if (dto.getOperation() == 0) {
            //点赞 operation=1
            //记录用户行为存储到redis

            //判断是否存在数据
            if (!redisTemplate.hasKey(key)) {
                redisTemplate.opsForValue().set(key, String.valueOf(dto.getOperation()));
                //调用文章ap_article数据库 修改状态 点赞+1
                ArticleDto articleDto = getArticleDto(dto);
                //三元运算
                articleDto.setLikes(articleDto.getLikes() == null ? 1 : articleDto.getLikes() + 1);
                //发起远程请求
                ResponseResult resp = articleClient.syncArticle(articleDto);
                if (resp.getCode() != 200) {
                    throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
                }
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //返回错误信息
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 不喜欢添加
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unLike(UnLikesBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        log.info("用户行为：{}", JSONObject.toJSONString(dto));
        // 从当前线程获取用户id
        Integer userId = ApThreadLocalUtil.get();
        //记录用户行为存储到redis
        //判断 tupe 0 不喜欢      1 取消不喜欢
        try {
            if (dto.getType() == 0) {
                //不喜欢
                String key = "unLike_" + userId + "_" + dto.getArticleId();
                redisTemplate.opsForValue().set(key, String.valueOf(dto.getType()));
            } else if (dto.getType() == 1) {
                //取消不喜欢
                String key = "unLike_" + userId + "_" + dto.getArticleId();
                redisTemplate.delete(key);
            }
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 获取文章信息
     * @param dto
     * @return
     */
    private ArticleDto getArticleDto(LikesBehaviorDto dto) {
        ArticleDto article = new ArticleDto();
        article.setId(dto.getArticleId());
        ResponseResult responseResult = articleClient.loadArticle(article);
        if (responseResult.getCode() != 200) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        得到 ArticleDto对象
        ArticleDto articleDto = JSON.parseObject(JSON.toJSONString(responseResult.getData()), ArticleDto.class);
        return articleDto;
    }

    /**
     * 收藏
     *
     * @param behaviorDto
     * @return
     */
    @Override
    public ResponseResult updateCollection(CollectionBehaviorDto behaviorDto) {
        //参数校验
        if (behaviorDto == null || behaviorDto.getEntryId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户id
        Integer userId = ApThreadLocalUtil.get();
        //拼装key
        String key = "collection_" + userId + "_" + behaviorDto.getEntryId();
        //查询redis 判断是否存在对应的数据
        if (redisTemplate.hasKey(key)) {
            //存在
            //判断 是收藏 还是取消收藏
            if (behaviorDto.getOperation() == 0) {
                //取消收藏
                redisTemplate.delete(key);

            } else if (behaviorDto.getOperation() == 1) {
                //收藏
                redisTemplate.opsForValue().set(key, String.valueOf(behaviorDto.getOperation()));
            }
        } else {

            //判断是收藏还是取消收藏
            if (behaviorDto.getOperation() == 0) {
                //取消收藏
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            } else if (behaviorDto.getOperation() == 1) {
                //收藏
                redisTemplate.opsForValue().set(key, String.valueOf(behaviorDto.getOperation()));
            }
        }
        //调用数据库
        ResponseResult result = articleClient.updateCollection(behaviorDto);
        if (result.getCode() != 200) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
